package userFileModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type createFolderRequest struct {
	FolderPid  model.SnowflakeIdType `json:"folderPid" binding:"required"`
	FolderName string                `json:"folderName" binding:"required"`
}

func (UserFileModuleApi) CreateFolder(c *gin.Context) {
	var req createFolderRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Errorf("CreateFolder bind json error:%v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	userId := utils.GetUserId(c)
	// 检查是否为根目录
	if req.FolderPid != 1 {
		var count int64 = 0
		query := global.DB.Model(&model.FileModel{}).Where("id=? and user_id=? and is_folder=? and del_flag=?",
			req.FolderPid, userId, enums.Folder, enums.Normal)
		if err := query.Count(&count).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				res.FailWithCode(res.FOLDER_NOT_EXIST, c)
				return
			}
			logrus.Errorf("count error:%v", err)
			res.FailWithCode(res.SYS_ERR, c)
			return
		}
		if count == 0 {
			res.FailWithCode(res.FOLDER_NOT_EXIST, c)
			return
		}
	}
	query := global.DB.Model(&model.FileModel{}).Where("file_pid=? and user_id=? and file_name=? and del_flag=? and is_folder=?",
		req.FolderPid, userId, req.FolderName, enums.Normal, enums.Folder)
	var count int64 = 0
	if err := query.Count(&count).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.Errorf("count error:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if count > 0 {
		res.FailWithCode(res.SAME_FOLDER_NAME_EXISTS, c)
		return
	}
	folder := model.FileModel{
		FilePid:      req.FolderPid,
		FileName:     req.FolderName,
		UserId:       userId,
		IsFolder:     enums.Folder,
		DelFlag:      enums.Normal,
		FilePath:     "",
		FileCover:    "",
		FileSize:     0,
		FileType:     0,
		FileMd5:      "",
		RecoveryTime: 0,
	}
	dbTransaction := global.DB.Begin()
	if err := dbTransaction.Create(&folder).Error; err != nil {
		logrus.Errorf("create folder error:%v", err)
		dbTransaction.Rollback()
		res.FailWithCode(res.CREATE_FOLDER_FAIL, c)
		return
	}
	if err := dbTransaction.Commit().Error; err != nil {
		logrus.Errorf("commit folder error:%v", err)
		dbTransaction.Rollback()
		res.FailWithCode(res.CREATE_FOLDER_FAIL, c)
		return
	}
	res.OkWithData(res.EmptyData, c)
}
